(function () {
    var datas = [
        {
            img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/2481d91110fb14bbfe2b8c07325cff97.jpg',
            link: 'https://www.baidu.com/',
        },
        {
            img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/72d2f359aa032bc5f6372b3022b39a92.jpg',
            link: 'https://www.jd.com/',
        },
        {
            img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/1e125f7e065bb9d7bc36b480a4437820.jpg',
            link: 'https://www.taobao.com/',
        },
        {
            img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/1484efbc954604f2fff16aa8a7447c3d.jpg',
            link: 'https://www.taobao.com/',
        },
    ];


    /**
     * 设置超链接的地址和图片路径
     * 动态生成span元素
     * 控制span元素的类样式
     */

    var indicator = document.querySelector('.carousel-indicator');
    var carouselLink = document.querySelector('.carousel a');
    var carouselImg = document.querySelector('.carousel a img');

    var leftarrow = document.querySelector('.carousel-leftarrow');
    var rightarrow = document.querySelector('.carousel-rightarrow');

    /**
     * 初始化 生成span元素
     */

    function init() {
        for (var i = 0; i < datas.length; i++) {
            var span = document.createElement('span');
            span.className = "fl";
            indicator.appendChild(span);
        }
        change(0);
    }
    init();


    /**
     * 将指定下标的数据显示到页面上
     */
    function change(index) {
        var d = datas[index];
        carouselLink.href = d.link;
        carouselImg.src = d.img;

        // span标签切换效果 先去除选中  再找添加选中、
        var selected = indicator.querySelector('.carousel-selected');
        if (selected) {
            selected.className = "fl"
        }
        var span = indicator.children[index];
        span.className = "fl carousel-selected";
    }



    // 目前显示第一张
    var curIndex = 0;

    /**
     * 向左翻
     */
    function toLeft() {
        curIndex--;
        if (curIndex < 0) {
            curIndex = datas.length - 1;
        }
        change(curIndex);
    }

    // 向右翻
    function toNext() {
        curIndex++;
        if (curIndex > datas.length - 1) {
            curIndex = 0;
        }
        change(curIndex);
    }


    // 注册事件
    leftarrow.onclick = toLeft;
    rightarrow.onclick = toNext;

    for (let i = 0; i < indicator.children.length; i++) {
        var span = indicator.children[i];
        span.onclick = function () {
            curIndex = i;
            change(i)
        }
    }


})();